﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

/// <summary>
/// 放到 Prefab 上，实现全部手势操作功能
/// </summary>
[RequireComponent(typeof(ARRaycastManager))]
public class GestureController2 : MonoBehaviour
{
    private Camera mARCamera;
    static List<ARRaycastHit> Hits;
    private ARRaycastManager mRaycastManager;
    private float mRotateSpeed = -20f;
    private float mZoomSpeed = 0.01f;
    private bool isValid = true;
#if UNITY_ANDROID
    private float mInitAngle = 180f;
#endif

    // Start is called before the first frame update
    void Start()
    {
        Hits = new List<ARRaycastHit>();
        GameObject arSessionObj = GameObject.Find("AR Session Origin");
        mRaycastManager = arSessionObj.GetComponent<ARRaycastManager>();
        mARCamera = GameObject.Find("AR Session Origin/AR Camera").GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        switch (Input.touchCount)
        {
            case 0: return;
            case 1: onSpawnObject(); onRotate(); break;
            case 2: onZoom(); break;
            default: return;
        }
    }

    private void onSpawnObject()
    {
        if (isValid)
        {
            isValid = !isValid;
#if UNITY_ANDROID
            //LogUtils.debug("GestureController2 onSpawnObject Rotate mInitAngle=" + mInitAngle);
            //this.transform.Rotate(new Vector3(0, mInitAngle, 0)); //点击的时候转了角度
#endif
        }
    }

    private void onZoom()
    {
        LogUtils.debug("GestureController2 onZoom()");
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);

        Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
        float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
        float deltaMagnitudeDiff = touchDeltaMag - prevTouchDeltaMag;

        float pinchAmount = deltaMagnitudeDiff * mZoomSpeed * Time.deltaTime;
        this.GetComponentInParent<Transform>().localScale += new Vector3(pinchAmount, pinchAmount, pinchAmount);
    }
    private void onRotate()
    {
        LogUtils.debug("GestureController2 onRotate()");
        Touch touch;
        touch = Input.GetTouch(0);
        if (Input.touchCount == 1 && touch.phase == TouchPhase.Moved)
        {
           this.GetComponentInParent<Transform>().Rotate(Vector3.up * mRotateSpeed * Time.deltaTime * touch.deltaPosition.x, Space.Self);
        }
    }

}
